package com.suda.controller;

import com.alibaba.fastjson.JSON;
import com.suda.pojo.Order;
import com.suda.service.OrderService;
import com.suda.service.WeixinPayService;
import com.github.wxpay.sdk.WXPayUtil;
import entity.Result;
import entity.StatusCode;
import org.junit.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/weixin/pay")
@CrossOrigin
public class WeixinPayController {
    @Value("${mq.pay.exchange.order}")
    private String exchange;
    @Value("${mq.pay.queue.order}")
    private String queue;
    @Value("${mq.pay.routing.key}")
    private String routing;

    @Autowired
    private WeixinPayService weixinPayService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderService orderService;


    /***
     * 创建二维码
     * @return
     */
    @RequestMapping(value = "/create/native")
    public Result createNative(@RequestParam Map<String,String> parameter){
        System.out.println("parameter==>"+parameter);
        Map<String,String> resultMap = weixinPayService.createNative(parameter);
        System.out.println("resultMap==>"+resultMap);
        return new Result(true, StatusCode.OK,"创建二维码预付订单成功！",resultMap);
    }
    /***
     * 查询支付状态
     * @param outtradeno
     * @return
     */
    @GetMapping(value = "/status/query")
    public Result queryStatus(String outtradeno){
        Map<String,String> resultMap = weixinPayService.queryPayStatus(outtradeno);

        return new Result(true, StatusCode.OK,"查询状态成功！",resultMap);
    }
    @GetMapping(value = "/close")
    public Result closePay(Long id){
        Map<String,String> resultMap = null;
        try {
            resultMap = weixinPayService.closePay(id);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Result(true, StatusCode.OK,"查询状态成功！",resultMap);
    }



    @RequestMapping(value = "/notify/url")
    public String notifyUrl(HttpServletRequest request){
        InputStream inStream;
        try {
            inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String s = new String(outSteam.toByteArray(), "utf-8");

            Map<String, String> map = WXPayUtil.xmlToMap(s);
            System.out.println("post"+map);
            String return_code =  map.get("return_code");
            //业务结果
            String result_code =  map.get("result_code");

            if(result_code==null||return_code==null)
            {
                Map respMap = new HashMap();
                respMap.put("return_code","SUCCESS");
                respMap.put("return_msg","OK");
                return WXPayUtil.mapToXml(respMap);
            }
            //业务结果 result_code=SUCCESS/FAIL，修改订单状态
            if(return_code.equalsIgnoreCase("success") ){
                //获取订单号
                String outtradeno = map.get("out_trade_no");
                Order order = new Order();
                order.setOrderId(outtradeno);
                order.setPayStatus("1");
                //业务结果
                if(result_code.equalsIgnoreCase("success")){
                    if(outtradeno!=null){
                        //修改订单状态  out_trade_no
                        orderService.update(order);
                    }
                }else{
                    //订单删除
                    orderService.delete(outtradeno);
                }
            }

            Map respMap = new HashMap();
            respMap.put("return_code","SUCCESS");
            respMap.put("return_msg","OK");
            return WXPayUtil.mapToXml(respMap);
        }catch (Exception e)
        {
        e.printStackTrace();

        }
        return null;
    }
}
